<template>
  <div class="profile-page page-container">
    <!-- 顶部导航 -->
    <div class="page-header">
      <a-button type="link" class="back-btn" @click="$router.back()">
        <a-icon type="left" />返回
      </a-button>
      <span class="title">个人信息</span>
      <a-button
        type="link"
        class="edit-btn"
        @click="handleEdit"
        v-if="!isEditing"
      >
        编辑
      </a-button>
    </div>

    <!-- 个人信息表单 -->
    <div class="profile-content">
      <a-spin :spinning="loading">
        <!-- 头像部分 -->
        <div class="avatar-section">
          <div class="avatar-wrapper">
            <a-avatar :size="80" :src="isEditing ? editForm.avatar : userInfo.avatar" icon="user" />
            <div class="avatar-edit" v-if="isEditing">
              <a-upload
                name="avatar"
                :show-upload-list="false"
                :before-upload="beforeUpload"
                accept="image/jpeg,image/png"
                :customRequest="() => {}"
                :auto-upload="false"
              >
                <a-icon type="camera" />
              </a-upload>
            </div>
          </div>
        </div>

        <!-- 信息列表 -->
        <div class="info-list">
          <div class="info-item">
            <span class="label">账号</span>
            <div class="value">
              <template v-if="!isEditing">{{ userInfo.account }}</template>
              <a-input
                v-else
                v-model="editForm.account"
                placeholder="请输入账号"
                disabled
              />
            </div>
          </div>

          <div class="info-item">
            <span class="label">昵称</span>
            <div class="value">
              <template v-if="!isEditing">{{ userInfo.nickName }}</template>
              <a-input
                v-else
                v-model="editForm.nickName"
                placeholder="请输入昵称"
              />
            </div>
          </div>

          <div class="info-item">
            <span class="label">手机号</span>
            <div class="value">
              <template v-if="!isEditing">{{ userInfo.phone }}</template>
              <a-input
                type="phone"
                v-else
                v-model="editForm.phone"
                placeholder="请输入手机号"
              />
            </div>
          </div>

          <div class="info-item">
            <span class="label">邮箱</span>
            <div class="value">
              <template v-if="!isEditing">{{ userInfo.email }}</template>
              <a-input
                v-else
                v-model="editForm.email"
                placeholder="请输入邮箱"
              />
            </div>
          </div>

          <div class="info-item">
            <span class="label">微信账号</span>
            <div class="value">
              <template v-if="!isEditing">{{
                userInfo.weChartAccount
              }}</template>
              <a-input
                v-else
                v-model="editForm.weChartAccount"
                placeholder="请输入微信账号"
              />
            </div>
          </div>

          <div class="info-item">
            <span class="label">用户类型</span>
            <div class="value">
              <template v-if="!isEditing">{{ userInfo.userType }}</template>
              <a-input
                v-else
                v-model="editForm.userType"
                placeholder="请输入用户类型"
                disabled
              />
            </div>
          </div>

          <template v-if="userInfo.userType === '分销用户'">
            <div class="info-item">
              <span class="label">消费限额</span>
              <div class="value">
                <template v-if="!isEditing">{{
                  userInfo.consumptionAmountLimit
                }}</template>
                <a-input-number
                  v-else
                  v-model="editForm.consumptionAmountLimit"
                  placeholder="请输入消费限额"
                  :min="0"
                />
              </div>
            </div>

            <div class="info-item">
              <span class="label">返现限额</span>
              <div class="value">
                <template v-if="!isEditing">{{
                  userInfo.cashbackAmountLimit
                }}</template>
                <a-input-number
                  v-else
                  v-model="editForm.cashbackAmountLimit"
                  placeholder="请输入返现限额"
                  :min="0"
                />
              </div>
            </div>
          </template>

          <div class="info-item">
            <span class="label">性别</span>
            <div class="value">
              <template v-if="!isEditing">{{
                genderText[userInfo.gender]
              }}</template>
              <a-radio-group v-else v-model="editForm.gender">
                <a-radio value="male">男</a-radio>
                <a-radio value="female">女</a-radio>
                <a-radio value="other">保密</a-radio>
              </a-radio-group>
            </div>
          </div>

          <div class="info-item">
            <span class="label">个性签名</span>
            <div class="value">
              <template v-if="!isEditing">{{ userInfo.signature }}</template>
              <a-textarea
                v-else
                v-model="editForm.signature"
                :rows="3"
                placeholder="请输入个性签名"
              />
            </div>
          </div>

          <div class="info-item">
            <span class="label">微信收款码</span>
            <div class="value">
              <img
                v-if="userInfo.wxQrCode"
                :src="userInfo.wxQrCode"
                alt="微信收款码"
                class="qr-code"
              />
              <span v-else class="no-qr-code">暂无收款码</span>
            </div>
          </div>
        </div>

        <!-- 编辑模式下的底部按钮 -->
        <div class="bottom-buttons" v-if="isEditing">
          <a-button @click="cancelEdit">取消</a-button>
          <a-button type="primary" @click="saveProfile">保存</a-button>
        </div>
      </a-spin>
    </div>
  </div>
</template>

<script>
import {
  Button,
  Icon,
  Avatar,
  Input,
  Radio,
  DatePicker,
  Upload,
  message,
  Spin,
  Form,
} from "ant-design-vue";
import { getUser, updateUser } from "@/api/user";
import { mapState, mapActions } from "vuex";

export default {
  name: "UserProfile",
  components: {
    AButton: Button,
    AIcon: Icon,
    AAvatar: Avatar,
    AInput: Input,
    ARadio: Radio,
    ARadioGroup: Radio.Group,
    ADatePicker: DatePicker,
    AUpload: Upload,
    ATextarea: Input.TextArea,
    ASpin: Spin,
    AForm: Form,
    AFormItem: Form.Item,
  },

  data() {
    return {
      loading: false,
      isEditing: false,
      editForm: {
        gender: "other",
      },
      userInfo: {
        pwd: "",
        passwordConfirm: "",
        phone: "",
        account: "",
        avatar: "",
        nickName: "",
        weChartAccount: "",
        email: "",
        userType: "",
        saleUserId: "",
        consumptionAmountLimit: 0,
        cashbackAmountLimit: 0,
        gender: "other",
        signature: "",
        wxQrCode: "",
      },
      genderText: {
        male: "男",
        female: "女",
        other: "保密",
      },
      formRules: {
        account: [{ required: true, message: "请输入账号", trigger: "blur" }],
        nickName: [{ required: true, message: "请输入昵称", trigger: "blur" }],
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "请输入正确的手机号",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { type: "email", message: "请输入正确的邮箱格式", trigger: "blur" },
        ],
        weChartAccount: [
          { required: true, message: "请输入微信账号", trigger: "blur" },
        ],
        consumptionAmountLimit: [
          { required: false, message: "请输入消费限额", trigger: "blur" },
          {
            type: "number",
            min: 0,
            message: "消费限额不能为负数",
            trigger: "blur",
          },
        ],
        cashbackAmountLimit: [
          { required: false, message: "请输入返现限额", trigger: "blur" },
          {
            type: "number",
            min: 0,
            message: "返现限额不能为负数",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.fetchUserInfo();
  },
  methods: {
    async fetchUserInfo(refreshUserCache = false) {
      this.loading = true;
      try {
       const response =  await getUser();
       if(response && response.code === 200){
        this.userInfo = response.data;
        if(refreshUserCache){
          this.$store.commit("user/setUerInfo", response.data);
        }
       }else{
        throw new Error(response?.msg || "获取用户信息失败");
       }
      } catch (error) {
        message.error("获取用户信息失败");
      } finally {
        this.loading = false;
      }
    },
    handleEdit() {
      this.isEditing = true;
      this.editForm = {
        ...this.userInfo,
        gender: this.userInfo.gender,
      };
    },
    cancelEdit() {
      this.isEditing = false;
      this.editForm = {
        gender: "other",
      };
    },
    async saveProfile() {
      try {
        this.loading = true;
        // 表单验证
        if (!this.editForm.account) {
          message.error("请输入账号");
          return;
        }
        if (!this.editForm.nickName) {
          message.error("请输入昵称");
          return;
        }
        if (!this.editForm.phone) {
          message.error("请输入手机号");
          return;
        }
        if (!this.editForm.email) {
          message.error("请输入邮箱");
          return;
        }
        if (!this.editForm.weChartAccount) {
          message.error("请输入微信账号");
          return;
        }
        if (!/^1[3-9]\d{9}$/.test(this.editForm.phone)) {
          message.error("请输入正确的手机号");
          return;
        }
        if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(this.editForm.email)) {
          message.error("请输入正确的邮箱格式");
          return;
        }
        
        // 确保头像是base64格式
        if (this.editForm.avatar && !this.editForm.avatar.startsWith('data:image')) {
          message.error("头像格式错误，请重新上传");
          return;
        }
        
        const response = await updateUser(this.editForm);
        if (response && response.code === 200) {
          this.isEditing = false;
          this.fetchUserInfo(true);
          message.success("保存成功");
        } else {
          throw new Error(response?.msg || "保存失败");
        }
      } catch (error) {
        message.error(error.message || "保存失败");
      } finally {
        this.loading = false;
      }
    },
    async beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        message.error('只能上传 JPG/PNG 格式的图片！')
        return false
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        message.error('图片必须小于 2MB！')
        return false
      }
      
      // 将图片转换为base64并立即显示
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => {
          this.editForm.avatar = reader.result
          resolve(false) // 阻止自动上传
        }
        reader.onerror = error => {
          message.error('图片转换失败')
          reject(error)
        }
      })
    },
  },
};
</script>

<style lang="less" scoped>
.profile-page {
  background: #fff;
  min-height: 100vh;
  width: 100vw;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 1000;

  .page-header {
    position: sticky;
    top: 0;
    z-index: 100;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 8px 12px;
    background: #fff;
    border-bottom: 1px solid #f0f0f0;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

    .title {
      font-size: 14px;
      font-weight: 500;
      color: #262626;
    }

    .back-btn {
      padding: 0;
      color: #1890ff;
    }

    .edit-btn {
      padding: 0;
      color: #1890ff;
    }
  }

  .profile-content {
    padding: 16px;
    max-width: 800px;
    margin: 0 auto;
    height: calc(100vh - 60px);
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
    padding-bottom: 80px; // 为底部按钮留出空间

    .avatar-section {
      text-align: center;
      margin-bottom: 24px;

      .avatar-wrapper {
        position: relative;
        display: inline-block;

        .avatar-edit {
          position: absolute;
          bottom: 0;
          right: 0;
          background: rgba(0, 0, 0, 0.5);
          width: 32px;
          height: 32px;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          cursor: pointer;
          transition: all 0.3s;

          &:hover {
            background: rgba(0, 0, 0, 0.7);
          }

          .anticon {
            color: #fff;
            font-size: 16px;
          }
        }
      }
    }

    .info-list {
      background: #fff;
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
      margin-bottom: 20px;

      .info-item {
        display: flex;
        padding: 12px 16px;
        border-bottom: 1px solid #f0f0f0;
        transition: all 0.3s;

        &:hover {
          background: #fafafa;
        }

        &:last-child {
          border-bottom: none;
        }

        .label {
          width: 80px;
          color: #8c8c8c;
          font-size: 14px;
          line-height: 32px;
          flex-shrink: 0;
        }

        .value {
          flex: 1;
          color: #262626;
          font-size: 14px;
          line-height: 32px;
          min-height: 32px;

          :deep(.ant-input),
          :deep(.ant-calendar-picker),
          :deep(.ant-input-number) {
            width: 100%;
          }

          :deep(.ant-radio-group) {
            line-height: 32px;
          }

          :deep(.ant-radio-wrapper) {
            margin-right: 16px;
          }

          :deep(.ant-textarea) {
            min-height: 80px !important;
          }

          .qr-code {
            max-width: 200px;
            border-radius: 4px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
          }

          .no-qr-code {
            color: #8c8c8c;
            font-size: 14px;
          }
        }
      }
    }
  }

  .bottom-buttons {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 12px 16px;
    background: #fff;
    box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.06);
    display: flex;
    justify-content: space-between;
    gap: 12px;
    z-index: 100;
    height: 68px; // 固定高度

    .ant-btn {
      flex: 1;
      height: 44px;
      font-size: 16px;
    }
  }
}

@media screen and (max-width: 768px) {
  .profile-page {
    .profile-content {
      padding: 12px;
      height: calc(100vh - 50px);

      .info-list {
        .info-item {
          padding: 10px 12px;

          .label {
            width: 70px;
            font-size: 13px;
          }

          .value {
            font-size: 13px;
          }
        }
      }
    }

    .bottom-buttons {
      padding: 8px 12px;
      height: 60px;

      .ant-btn {
        height: 40px;
        font-size: 14px;
      }
    }
  }
}
</style>
